package com.example.zookeeper.demo;

import com.example.zookeeper.core.ZkCore;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ChildWatcher
{
    private final ZkCore zkCore;

    @Autowired
    public ChildWatcher(ZkCore zkCore)
    {
        this.zkCore = zkCore;
    }

    public void start()
    {
        String path = "/test";

        try
        {
            if (zkCore.exist(path) == null)
            {
                zkCore.createNode(path, "hello zookeeper".getBytes(), CreateMode.PERSISTENT);
            }
            else
            {
                System.out.println("node /test has exist!");
            }
            getChildNodes(path);
        } catch (KeeperException | InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    private void getChildNodes(String path)
    {
        try
        {
            List<String> childrenNodes = zkCore.getChildNodes(path, watchedEvent ->
                    getChildNodes(path));
            System.out.println(childrenNodes);
        } catch (KeeperException | InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}
